'use client';

import type { IPostEditInfo, IQueryAllHistoryByPostId } from '@/interfaces';
import { useQuery } from '@tanstack/react-query';
import { queryAllHistoryByPostId } from '@/services/api';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import { useRef, useState } from 'react';
import type diff_match_patch from 'diff-match-patch';
import { flushSync } from 'react-dom';
import classNames from 'classnames';
import { formatDate } from '@/lib/tool';
import CreateHistory, {
  type TCreateHistoryTranslatedField,
} from '@/app/[locale]/posts/[id]/edit/history/create';
import ViewHistory, {
  type TViewHistoryTranslatedField,
} from '@/app/[locale]/posts/[id]/edit/history/view';

export type THistoryTranslatedField = 'nodata';

export default function History(
  this: any,
  {
    source,
    translatedFields = {
      nodata: '暂无历史',
    },
    createTranslatedFields,
    viewTranslatedFields,
  }: {
    source: IPostEditInfo;
    translatedFields?: Record<THistoryTranslatedField, any>;
    createTranslatedFields?: Record<TCreateHistoryTranslatedField, any>;
    viewTranslatedFields?: Record<TViewHistoryTranslatedField, any>;
  },
) {
  const [loadDiffMatchPatch, setLoadDiffMatchPatch] = useState(false);
  const diffMatchPatchRef = useRef<diff_match_patch>();
  const [currentHistoryKey, setCurrentHistoryKey] = useState<string>();
  const queryKey = ['/forum', '/histories', '/posts', source.basic.id];
  const [currentHistoryId, setCurrentHistoryId] = useState<number>();

  const queryAllHistoryByPostIdQuery = useQuery(queryKey, async (context) => {
    return (await queryAllHistoryByPostId({
      id: context.queryKey[3] + '',
    })) as IQueryAllHistoryByPostId;
  });

  async function onClickHistory(item: string) {
    if (!diffMatchPatchRef.current) {
      await flushSync(async () => {
        setLoadDiffMatchPatch(true);
        const diffMatchPatch = (await import('diff-match-patch')).default;
        diffMatchPatchRef.current = new (diffMatchPatch as any)();
        setLoadDiffMatchPatch(false);
        setCurrentHistoryKey(item);
      });
    } else {
      setCurrentHistoryKey(item);
    }
  }

  function onClickItem(id: number) {
    setCurrentHistoryId(id);
  }

  if (queryAllHistoryByPostIdQuery.data) {
    const historyList = queryAllHistoryByPostIdQuery.data;
    const historyKeys = Object.keys(historyList);

    return (
      <div className="card border-0">
        <div className="card-body d-flex flex-column gap-4 my-4">
          <CreateHistory
            queryKey={queryKey}
            id={source.basic.id}
            translatedFields={createTranslatedFields}
          />

          <div className="row mt-4 g-4">
            <div className="col-12 col-lg">
              {historyKeys.length > 0 && (
                <div className="list-group">
                  {historyKeys.map((item) => {
                    return (
                      <div
                        key={item}
                        className={classNames(
                          'card border text-secondary border-1 mb-3 list-group-item list-group-item-action cursor-pointer',
                          {
                            active: currentHistoryKey === item,
                          },
                        )}
                        onClick={onClickHistory.bind(this, item)}
                      >
                        <div className="card-body px-0 py-2">
                          {loadDiffMatchPatch ? (
                            <div className="hstack text-white">
                              <span
                                style={{ width: '2rem', height: '2rem' }}
                                className="spinner-border spinner-border-sm me-2 flex-shrink-0"
                                role="status"
                                aria-hidden="true"
                              ></span>
                              <span className="text-truncate">Loading...</span>
                            </div>
                          ) : (
                            <div className="row">
                              <div className="col-3 m-auto text-center ms-0">
                                <i
                                  className={classNames(
                                    'bi bi-clock-history fs-2',
                                    currentHistoryKey === item
                                      ? 'text-white'
                                      : 'text-secondary',
                                  )}
                                ></i>
                              </div>
                              <div className="col-8 align-self-center">
                                <p
                                  className={classNames(
                                    'card-title mb-0 text-truncate',
                                    currentHistoryKey === item
                                      ? 'text-white'
                                      : 'text-secondary',
                                  )}
                                >
                                  {formatDate(item)}
                                </p>
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}

              {historyKeys.length === 0 && (
                <Alert message={translatedFields.nodata} />
              )}
            </div>

            {currentHistoryKey && (
              <div className="col">
                <div className="list-group">
                  {historyList[currentHistoryKey].map((item, index) => {
                    return (
                      <button
                        key={item.id}
                        type="button"
                        className={classNames(
                          'list-group-item list-group-item-action text-truncate',
                          {
                            active: currentHistoryId === item.id,
                          },
                        )}
                        onClick={onClickItem.bind(this, item.id)}
                      >
                        <time dateTime={item.createdOn}>
                          {`${formatDate(item.createdOn)} v${
                            historyList[currentHistoryKey].length - index
                          }`}
                        </time>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {currentHistoryId && (
              <div className="col-12">
                <ViewHistory
                  id={currentHistoryId}
                  diffMatchPatchRef={diffMatchPatchRef}
                  translatedFields={viewTranslatedFields}
                />
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  if (queryAllHistoryByPostIdQuery.error) {
    return <Alert type="error" message={queryAllHistoryByPostIdQuery.error} />;
  }

  return <AlertLoad />;
}
